package com.sd365.permission.centre.service.util;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BizErrorCode;
import com.sd365.common.core.common.exception.code.CommonErrorCode;
import com.sd365.common.core.mq.MqDataSyncMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OMSTenant {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(autoDelete = "false"),
                    key = {"tenant"},
                    exchange = @Exchange(name = "directs",type = "direct"))
    })

    public void test02_receive(Channel channel, Message message) throws Exception {
        String jsonString = new String(message.getBody());
        Object tag = message.getMessageProperties().getDeliveryTag();
        System.out.println(Thread.currentThread().getName()+"接收到来自direct.monitor队列的Tag: "+message.getMessageProperties().getDeliveryTag());
        MqDataSyncMsg mqDataSyncMsg = JSON.parseObject(jsonString, MqDataSyncMsg.class);
        System.out.println(Thread.currentThread().getName()+"接收到来自direct.monitor队列的message消息: "+mqDataSyncMsg);
        if(mqDataSyncMsg != null){
            if (mqDataSyncMsg.getDataList().size()>0){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                System.out.println("消息"+tag+"从rabbitmq队列中消费成功!");
            }else {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                log.info("消息"+tag+"从rabbitmq队列中消费成功!");
                throw new BusinessException(BizErrorCode.DATA_SEARCH_NOT_FOUND, new Exception("rabbitmq消息队列内容为空"));
            }
        }else {
            System.out.println("error....");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("消息"+tag+"消费失败,并重新返回到rabbitmq队列中!");
        }

    }
}
